var MOCK = false;
var root_url = "/bookstoreOnline"
if (MOCK) {
    document.write('<script src="../js/mock.js" type="text/javascript" charset="utf-8"></script>');
    document.write('<script src="../testAPI/userAPI.js" type="text/javascript" charset="utf-8"></script>');
}
//书本行
let $book_cols;
//书本数据
let books;
//当前页
let current_page = 1;
//当前列
let current_col = 0;
//书本查询字符串
let current_b_SStr = "";
//分类查询字符串
let current_c_SStr = "";
//滚动延迟标志
let scroll_coll_flag = true;
//购物车表
let $shopping_cart_table;
//购物车表行对象
let rows;
//用户订单表
let $order_user_table;
let $order_detail_table;

window.onload = function () {
    nav_changer_listener();
    $book_cols = document.getElementsByClassName("col");
    add_scroll_listener();
    get_books(current_page, current_b_SStr, null, "init");
}

function add_scroll_listener() {
    document.addEventListener('scroll', function () {
        let ele = document.documentElement; // 获得html
        let scrollTop = ele.scrollTop; // 向上滚动的高度
        let scrollHeight = ele.scrollHeight; // 滚动内容区域总高度
        let clientHeight = ele.clientHeight; // 可见高度
        //TODO 高度原因，若一开始没有多少书籍，可能无法触发滚动事件
        if (clientHeight + scrollTop >= scrollHeight) { // 已经滚动到底部
            if (scroll_coll_flag === true) {
                get_books(current_page, current_b_SStr, null, "append");
                current_page++;
                scroll_coll_flag = false;
                setTimeout(function () {
                    scroll_coll_flag = true;
                }, 1000);　　　　//延时10秒
            }
        }
    })
}

function nav_changer_listener() {
    let breadcrumb_items = document.getElementsByClassName("breadcrumb-item");
    for (i = 0; i < breadcrumb_items.length; i++) {
        breadcrumb_items[i].onclick = function () {
            breadcrumb_items[0].innerHTML = `<a href="#">图书商城</a>`;
            breadcrumb_items[1].innerHTML = `<a href="#">我的购物车</a>`;
            breadcrumb_items[2].innerHTML = `<a href="#">我的订单</a>`;

            let book_warp = document.getElementsByClassName("book-warp");
            let shopping_cart_warp = document.getElementsByClassName("shopping-cart-warp");
            let order_user_warp = document.getElementsByClassName("order-user-warp");
            book_warp[0].style.display = "none";
            shopping_cart_warp[0].style.display = "none";
            order_user_warp[0].style.display = "none";

            value = this.value;
            let op_name;
            if (value == "1") {
                op_name = "图书商城"
                this.innerHTML = op_name;
                book_warp[0].style.display = "block";
                scroll_coll_flag = true;
            }
            if (value == "2") {
                op_name = "我的购物车"
                this.innerHTML = op_name;
                shopping_cart_warp[0].style.display = "block";
                scroll_coll_flag = false;
                init_shopping_cart_table();
            }
            if (value == "3") {
                op_name = "我的订单"
                this.innerHTML = op_name;
                order_user_warp[0].style.display = "block"
                scroll_coll_flag = false;
                init_order_user_table()
            }

        }
    }
}

//获取书籍信息
function get_books(...value) {
    $.ajaxSettings.async = true;//设置同步
    let page_num = value[0] == null ? null : value[0];
    let b_name_sstr = value[1] == null ? null : value[1];
    let c_name_sstr = value[2] == null ? null : value[2];
    $.post(root_url + "/get/book/table", {
        page_num: page_num,
        b_name_sstr: b_name_sstr,
        c_name_sstr: c_name_sstr
    }, function (res, status) {
        res = JSON.parse(res);
        if (status === "success") {
            if (res.code == "1") {
                books = res.rows;
                if (value[3] == "init") {
                    book_table_generate_op("init");
                }
                if (value[3] == "append") {
                    book_table_generate_op("append");
                }
                if (value[3] == "s_by_name") {
                    console.log(books);
                    book_table_generate_op("init");
                }
            }
        }
    })
}

//在以获取表格数据的情况下,对表格进行操作
function book_table_generate_op(op) {
    //初始化
    if (op === "init") {
        //清空col
        for (let i = 0; i < $book_cols.length; ++i) {
            book_col_op("clear", $book_cols[i]);
            current_col = 0;
        }
        for (let i = current_col; i < books.length; ++i) {
            current_col = i % 4 + 1;
            book_col_op("append_one", $book_cols[i % 4], books[i]);
        }
    }
    if (op === "clear") {
        //清空col
        for (let i = 0; i < $book_cols.length; ++i) {
            book_col_op("clear", $book_cols[i]);
        }
    }
    if (op === "append") {
        for (let i = current_col; i < books.length; ++i) {
            current_col = i % 4 + 1;
            book_col_op("append_one", $book_cols[i % 4], books[i]);
        }
    }
}

//对瀑布流每一行的操作
function book_col_op(op, col, my_books) {
    //清空操作
    if (op === "clear") {
        col.innerHTML = "";
    }
    //追加
    if (op === "append_one") {
        col.innerHTML += book_card_generate(my_books);
    }
}

//生成书籍卡片div
function book_card_generate(book) {
    let result;
    result = `
    <div class="card mb-3" style="width: 15rem;">
        <img src="${root_url}/staticFilepath/img/book/${book.imageName}" class="card-img-top" alt="...">
        <div class="card-body">
            <h5 class="card-title">${book.b_name}</h5>
            <p class="card-text">${book.description}</p>
            <div>分类:&nbsp;${book.c_name}</div>
            <div>单价:&nbsp;${book.price}</div>
            <a href="javascript:(0)" class="btn btn-primary" onclick="add_shopping_cart('${book.b_id}')">加入购物车</a>
        </div>
    </div>
    `
    return result;
}

//通过姓名查找字符串
function search_by_SStr() {
    //获取输入框的数据
    current_b_SStr = $("#b-name-SStr").val();
    current_c_SStr = $("#c-name-SStr").val();
    current_page = 1;
    get_books(current_page, current_b_SStr, current_c_SStr, "s_by_name");
    current_page++;
}

function add_shopping_cart(b_id) {
    console.log(b_id)
    $.post(root_url + "/op/order/item", {
        b_id: b_id,
        b_num: "1",
    }, function (res, status) {
        if (status === "success") {
            res = JSON.parse(res);
            if (res.code === "0") {
                alert(res.msg);
            } else {
                alert(res.msg);
            }
        }
    })
}

function shopping_cart_op(row, op) {
    console.log(row);
    if (op === "refresh") {
        $shopping_cart_table.bootstrapTable("refresh");
    }
    if (op === "delete") {
        let row_data = $shopping_cart_table.bootstrapTable('getData')[row.dataset["index"]];
        let item_id = row_data.item_id;
        let item_price = row.childNodes[3].innerHTML;
        $.post(root_url + "/delete/order/item", {
            item_id: item_id,
            item_price: item_price
        }, function (res, status) {
            if (status === "success") {
                res = JSON.parse(res);
                if (res.code == "0") {
                    alert("未知错误")
                } else {
                    console.log("删除成功")
                    $shopping_cart_table.bootstrapTable("refresh");
                }
            }
        })
    }
    if (op === "change_num") {
        let row_data = $shopping_cart_table.bootstrapTable('getData')[row.dataset["index"]];
        let b_id = row_data.b_id;
        let b_num = row.childNodes[1].childNodes[0].value;
        console.log(b_num)
        //提交修改数据
        $.post(root_url + "/op/order/item", {
            b_id: b_id,
            b_num: b_num,
        }, function (res, status) {
            if (status === "success") {
                res = JSON.parse(res);
                if (res.code == "1") {
                    console.log("修改成功");
                    $shopping_cart_table.bootstrapTable("refresh");
                } else {
                    alert("位置错误");
                }
            }
        })
    }
    if (op === "pay") {
        $.post(root_url + "/pay/order", {}, function (res, status) {
            if (status === "success") {
                res = JSON.parse(res);
                if (res.code == "0") {
                    alert(res.msg);
                } else {
                    alert(res.msg);
                    $shopping_cart_table.bootstrapTable("refresh");
                    $order_user_table.bootstrapTable('refresh');
                }
            }
        })
    }
}

function init_shopping_cart_table() {
    $shopping_cart_table = $('#shopping-cart-table').bootstrapTable({
        url: root_url + '/get/order/item/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbarAlign: 'left', //工具栏的位置
        toolbar: '#shopping-cart-toolbar', //工具栏
        onLoadSuccess: function () {
            //TODO 当没有数据的时候，不允许生成监听表
            get_shopping_table_ele();
        },
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                orderId: "",
            };
        },
        columns: [{
            field: 'b_name',
            title: '书本名称',
        }, {
            field: 'b_num',
            title: '书本数量',
            width: 150,
            formatter: function (value, row, index) {
                return shopping_cart_table_formatter(value, row, index, 'b_num')
            },
        }, {
            field: 'b_price',
            title: '书本单价',
        }, {
            field: 'i_price',
            title: '总价',
            width: 200,
        }, {
            field: 'item_id',
            title: '可供操作',
            align: 'center',
            valign: 'middle',
            width: 400,
            formatter: function (value, row, index) {
                return shopping_cart_table_formatter(value, row, index, 'offer')
            },
        },]
    });
}

function shopping_cart_table_formatter(value, row, index, op) {
    let result = ``;
    if (op === "offer") {
        result = `<button type="button" class="btn btn-danger">删除</button>
                <button type="button" class="btn btn-warning item-change-btn">修改</button>`
    }
    if (op === "b_num") {
        result = `<input type="text" class="form-control book-num" value="${value}" disabled="true">`;
    }
    return result;
}

function get_shopping_table_ele() {
    rows = document.getElementById("shopping-cart-table").childNodes[2].childNodes;
    //设置当前行修改按钮的点击事件
    for (let i = 0; i < rows.length; ++i) {
        rows[i].childNodes[4].childNodes[2].onclick = function () {
            change_btn_listener(rows[i]);
        }
    }
    for (let i = 0; i < rows.length; ++i) {
        rows[i].childNodes[4].childNodes[0].onclick = function () {
            delete_btn_listener(rows[i]);
        }
    }
}

function change_btn_listener(row) {
    //当为修改时，说明用户想要修改
    if (row.childNodes[4].childNodes[2].innerHTML === "修改") {
        row.childNodes[4].childNodes[2].innerHTML = "确认修改";
        row.childNodes[1].childNodes[0].disabled = false;
        $(row.childNodes[1].childNodes[0]).bind('input propertychange', function () {
            let row_data = $shopping_cart_table.bootstrapTable('getData')[row.dataset["index"]];
            row.childNodes[3].innerHTML = row_data.b_price * row.childNodes[1].childNodes[0].value;
        })
    }
    //此时用户应该提交了修改
    else {
        row.childNodes[4].childNodes[2].innerHTML = "修改";
        row.childNodes[1].childNodes[0].disabled = true;
        shopping_cart_op(row, "change_num");
    }
}

function delete_btn_listener(row) {
    shopping_cart_op(row, "delete");
}

function init_order_user_table() {
    $order_user_table = $('#order-user-table').bootstrapTable({
        url: root_url + '/get/order/info/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbar: '#order-user-toolbar', //工具栏
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                role: "user",
            };
        },
        columns: [{
            field: 'orderId',
            title: '订单号',
        }, {
            field: 'info_num',
            title: '条目数量',
        }, {
            field: 'info_price',
            title: '订单总价格',
        }, {
            field: 'status',
            title: '订单状态',
            formatter: function (value, row, index) {
                return order_user_table_formatter(value, row, index, 'status')
            },
        }, {
            field: 'orderId',
            title: '可供操作',
            align: 'left',
            valign: 'middle',
            width: 400,
            formatter: function (value, row, index) {
                return order_user_table_formatter(value, row, index, 'offer')
            },
        },]
    });
}

function order_user_table_formatter(value, row, index, op) {
    let result;
    if (op == "offer") {
        if (row.status === "0") {
            result = `<button type="button" class="btn btn-success" onclick="shopping_cart_op(0,'pay')">确认付款</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_user_op('${row.orderId}','detail')">详细信息</button>`
        } else if (row.status === "1" || row.status === "3" || row.status === "4") {
            result = `<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_user_op('${row.orderId}','detail')">详细信息</button>`;
        } else if (row.status === "2") {
            result = `<button type="button" class="btn btn-danger" onclick="order_user_op('${row.orderId}','refund')">申请退款</button>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#order-detail-modal" onclick="order_user_op('${row.orderId}','detail')">详细信息</button>`
        }
    } else if (op = "status") {
        if (value == "0") {
            result = "未付款"
        } else if (value == "1") {
            result = "未发货"
        } else if (value == "2") {
            result = "已发货"
        } else if (value == "3") {
            result = "待处理"
        } else if (value == "4") {
            result = "已撤销"
        }
    }
    return result;
}

function order_user_op(...value) {
    if (value[1] === "refresh") {
        $order_user_table.bootstrapTable("refresh");
    }
    if (value[1] === "detail") {
        if ($order_detail_table == null) {
            init_order_detail_table(value[0]);
        } else {
            $order_detail_table.bootstrapTable('destroy');
            init_order_detail_table(value[0]);
        }
    }

    if (value[1] === "refund") {
        $.post(root_url + "/op/order/status", {
            orderId: value[0],
            des_status: "3"
        }, function (res, status) {
            res = JSON.parse(res)
            if (res.line == "1") {
                alert("申请退货成功");
                $order_user_table.bootstrapTable('refresh');
            } else {
                alert("操作失败");
            }
        })
    }
}

function init_order_detail_table(orderId) {
    $order_detail_table = $('#order-detail-table').bootstrapTable({
        url: root_url + '/get/order/item/table',
        method: "post",
        search: true, //是否显示表格搜索
        sidePagination: "client", //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,
        pageSize: 5, //每页的记录行数（*）
        pageList: [10, 25, 50, 100], //可供选择的每页的行数（*）
        pagination: true, //是否显示分页（*）
        height: 560,
        singleSelect: false,
        contentType: "application/x-www-form-urlencoded", //发送给服务器的编码类型
        toolbarAlign: 'left', //工具栏的位置
        //得到查询的参数
        queryParams: function (params) {
            //这里的键的名字和控制器的变量名必须一致，这边改动，控制器也需要改成一样的
            return {
                rows: params.limit, //页面大小
                page: (params.offset / params.limit) + 1, //页码
                sort: params.sort, //排序列名
                sortOrder: params.order, //排位命令（desc，asc）
                orderId: orderId,
            };
        },

        columns: [{
            field: 'b_name',
            title: '书本名称',
        }, {
            field: 'b_num',
            title: '书本数量',
        }, {
            field: 'i_price',
            title: '总价',
        },]
    });
}

function quit() {
    //TODO 清除存留的session
    $.post(root_url + "/quit", {}, function () {
        window.location = ".." + root_url + "/";
    });
}